const ws = require('nodejs-websocket')
console.log('开始建立连接...')

let game1 = null; let game2 = null; let game1Ready = false; let game2Ready = false
const server = ws.createServer(function (conn) {
  conn.on('text', function (str) {
    console.log('收到的信息为:' + str)
    if (str === '心跳测试') {
      conn.sendText('收到心跳检测了')
    }
    if (str === 'close') {
      conn.sendText('----我要关闭了----')
      setTimeout(() => {
        conn.close()
      }, 2000)
    }
    if (str === 'game1') {
      game1 = conn
      game1Ready = true
      conn.sendText('success')
    }
    if (str === 'game2') {
      game2 = conn
      game2Ready = true
    }

    if (game1Ready && game2Ready) {
      game2.sendText(str)
    }

    conn.sendText('socket返回：' + str)
  })
  conn.on('close', function (code, reason) {
    console.log('关闭连接')
  })
  conn.on('error', function (code, reason) {
    console.log('异常关闭')
  })
}).listen(9000)
console.log('WebSocket建立完毕')
